import 'package:flutter/material.dart';
import 'package:fishing/models/app_version.dart';
import 'package:fishing/services/version_service.dart';

class VersionProvider extends ChangeNotifier {
  final VersionService _versionService = VersionService();
  
  bool _isChecking = false;
  bool _isDownloading = false;
  double _downloadProgress = 0.0;
  CheckUpdateResponse? _updateResponse;
  String? _errorMessage;
  Map<String, String>? _currentVersionInfo;
  bool _hasDownloadedFile = false;
  String? _downloadedApkPath;

  bool get isChecking => _isChecking;
  bool get isDownloading => _isDownloading;
  double get downloadProgress => _downloadProgress;
  CheckUpdateResponse? get updateResponse => _updateResponse;
  String? get errorMessage => _errorMessage;
  Map<String, String>? get currentVersionInfo => _currentVersionInfo;
  bool get hasDownloadedFile => _hasDownloadedFile;
  String? get downloadedApkPath => _downloadedApkPath;

  /// 初始化版本信息
  Future<void> initVersionInfo() async {
    try {
      _currentVersionInfo = await _versionService.getCurrentVersionInfo();
      notifyListeners();
    } catch (e) {
    }
  }

  /// 检查版本更新
  Future<void> checkUpdate({bool forceCheck = false, bool showNoUpdateMessage = false}) async {
    if (_isChecking) return;

    _isChecking = true;
    _errorMessage = null;
    notifyListeners();

    try {
      final response = await _versionService.checkUpdate(forceCheck: forceCheck);
      _updateResponse = response;
      
      
      // 如果有更新，检查是否已下载过对应的APK文件
      if (response.hasUpdate && response.latestVersion != null) {
        await _checkDownloadedFile();
      }
      
      if (!response.hasUpdate && showNoUpdateMessage) {
        _errorMessage = '当前已是最新版本';
      }
    } catch (e) {
      _errorMessage = '检查更新失败: $e';
    } finally {
      _isChecking = false;
      notifyListeners();
    }
  }

  /// 检查是否已下载对应版本的APK文件
  Future<void> _checkDownloadedFile() async {
    if (_updateResponse?.latestVersion == null) return;
    
    try {
      final latestVersion = _updateResponse!.latestVersion!;
      final fileName = latestVersion.fileName ?? 'app_${latestVersion.versionName}.apk';
      
      final cachedPath = await _versionService.getDownloadedApkPath(
        latestVersion.downloadUrl!,
        fileName,
        expectedFileSize: latestVersion.fileSize,
      );
      
      _hasDownloadedFile = cachedPath != null;
      _downloadedApkPath = cachedPath;
      
    } catch (e) {
      _hasDownloadedFile = false;
      _downloadedApkPath = null;
    }
  }

  /// 开始下载更新
  Future<void> startDownload() async {
    if (_updateResponse?.latestVersion?.downloadUrl == null) {
      _errorMessage = '下载链接无效';
      notifyListeners();
      return;
    }

    _isDownloading = true;
    _downloadProgress = 0.0;
    _errorMessage = null;
    notifyListeners();

    try {
      final latestVersion = _updateResponse!.latestVersion!;
      
      // 记录开始下载日志
      await _versionService.recordUpdateLog(
        targetVersion: latestVersion.versionName,
        updateStatus: 'downloading',
      );

      // 生成APK文件名
      final fileName = latestVersion.fileName ?? 'app_${latestVersion.versionName}.apk';
      
      // 下载APK文件
      final filePath = await _versionService.downloadApk(
        latestVersion.downloadUrl!,
        fileName,
        expectedFileSize: latestVersion.fileSize,
        onProgress: (progress) {
          _downloadProgress = progress;
          notifyListeners();
        },
      );
      
      _downloadedApkPath = filePath;
      _hasDownloadedFile = true;
      
      // 记录下载完成日志
      await _versionService.recordUpdateLog(
        targetVersion: latestVersion.versionName,
        updateStatus: 'download_completed',
      );

      // 开始安装
      _errorMessage = '正在安装...';
      notifyListeners();
      
      await _versionService.recordUpdateLog(
        targetVersion: latestVersion.versionName,
        updateStatus: 'installing',
      );

      final installSuccess = await _versionService.installApk(filePath);
      
      if (installSuccess) {
        await _versionService.recordUpdateLog(
          targetVersion: latestVersion.versionName,
          updateStatus: 'install_completed',
        );
        _errorMessage = '安装成功，请重启应用';
      } else {
        throw Exception('安装失败');
      }

    } catch (e) {
      _errorMessage = '更新失败: $e';
      await _versionService.recordUpdateLog(
        targetVersion: _updateResponse!.latestVersion!.versionName,
        updateStatus: 'failed',
        errorMessage: e.toString(),
      );
    } finally {
      _isDownloading = false;
      notifyListeners();
    }
  }


  /// 跳过当前版本
  Future<void> skipCurrentVersion() async {
    if (_updateResponse?.latestVersion != null) {
      await _versionService.skipVersion(_updateResponse!.latestVersion!.versionName);
      _updateResponse = null;
      notifyListeners();
    }
  }

  /// 清除错误信息
  void clearError() {
    _errorMessage = null;
    notifyListeners();
  }

  /// 清除更新响应
  void clearUpdateResponse() {
    _updateResponse = null;
    notifyListeners();
  }

  /// 直接安装已下载的APK文件
  Future<void> installDownloadedApk() async {
    if (!_hasDownloadedFile || _downloadedApkPath == null) {
      _errorMessage = '没有找到已下载的安装包';
      notifyListeners();
      return;
    }

    try {
      _errorMessage = '正在安装...';
      notifyListeners();
      
      // 记录安装开始日志
      if (_updateResponse?.latestVersion != null) {
        await _versionService.recordUpdateLog(
          targetVersion: _updateResponse!.latestVersion!.versionName,
          updateStatus: 'installing',
        );
      }

      final installSuccess = await _versionService.installApk(_downloadedApkPath!);
      
      if (installSuccess) {
        if (_updateResponse?.latestVersion != null) {
          await _versionService.recordUpdateLog(
            targetVersion: _updateResponse!.latestVersion!.versionName,
            updateStatus: 'install_completed',
          );
        }
        _errorMessage = '安装成功，请重启应用';
      } else {
        throw Exception('安装失败');
      }

    } catch (e) {
      _errorMessage = '安装失败: $e';
      if (_updateResponse?.latestVersion != null) {
        await _versionService.recordUpdateLog(
          targetVersion: _updateResponse!.latestVersion!.versionName,
          updateStatus: 'install_failed',
          errorMessage: e.toString(),
        );
      }
    } finally {
      notifyListeners();
    }
  }

  /// 清理下载缓存
  Future<void> clearDownloadCache() async {
    try {
      await _versionService.clearDownloadCache();
      _hasDownloadedFile = false;
      _downloadedApkPath = null;
      notifyListeners();
    } catch (e) {
    }
  }

  /// 应用启动时自动检查更新
  Future<void> autoCheckOnAppStart() async {
    // 延迟3秒后自动检查，避免影响应用启动速度
    await Future.delayed(const Duration(seconds: 3));
    await checkUpdate(forceCheck: false);
  }
}